package com.sara.loader;

import java.util.Map;

import org.apache.http.client.methods.HttpRequestBase;

import com.sara.util.loader.IMakeHttpHead;
import com.sara.util.loader.UrlLoader;

import android.content.Context;

public class Sender {

	private Context mContext;
	private Request requestObject;
	private ResponseParser responseParser;

	public Sender(Context context, Request requestObject,
			ResponseParser responseParser) {
		this.mContext = context;
		this.requestObject = requestObject;
		this.responseParser = responseParser;
	}

	public void send() {
		UrlLoader loader = UrlLoader.getDefault(mContext);
		loader.loadUrl(requestObject.getRequestUrl(), getPostData(),
				new MakeHttpHead(requestObject.getRequestHeaders()),
				responseParser);
	}

	private String getPostData() {
		if (requestObject == null) {
			return null;
		}
		if (requestObject.getRequestData() == null
				|| requestObject.getRequestData().isEmpty()) {
			return null;
		}
		StringBuffer result = new StringBuffer();
		for (Map.Entry<String, String> entry : requestObject.getRequestData()
				.entrySet()) {
			if (result.length() != 0) {
				result.append("&");
			}
			result.append(entry.getKey()).append("=").append(entry.getValue());
		}
		return result.toString();
	}

	private class MakeHttpHead extends IMakeHttpHead {

		private Map<String, String> requestHeaders;

		public MakeHttpHead(Map<String, String> requestHeaders) {
			this.requestHeaders = requestHeaders;
		}

		@Override
		public void makeHttpHead(HttpRequestBase hr, boolean isgzip) {
			if (requestHeaders != null && hr != null
					&& !requestHeaders.isEmpty()) {
				for (Map.Entry<String, String> entry : requestHeaders
						.entrySet()) {
					hr.addHeader(entry.getKey(), entry.getValue());
				}
			}
		}

	}
}
